
<template>
  <div class='repairRecord_container'>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <div style="margin-bottom: 10px;">
          <el-switch v-model="condition.queryType" active-text="独立查询" inactive-text="组合查询"
            inactive-color="#F56C6C" title="独立查询条件互斥，反之兼并">
          </el-switch>
          <el-button type="primary" @click="reset">
            <i class="fa fa-repeat" aria-hidden="true"></i>&nbsp;重置
          </el-button>
        </div>
        <el-row style="margin-bottom: 5px;">
          <el-col :xs="24" :sm="6" :md="6" :lg="6" :xl="6">
            <div style="display: inline-block;">
              <el-input placeholder="订单号" v-model="condition.orderId" clearable>
              </el-input>
            </div>
            <el-button type="primary" @click="queryWorkerOrder(condition.orderId)">
              <i class="fa fa-search" aria-hidden="true"></i>&nbsp;查询订单号
            </el-button>
          </el-col>
        </el-row>
        <el-row style="margin-bottom: 5px;">
          <el-col :xs="24" :sm="6" :md="6" :lg="6" :xl="6">
            <el-select v-model="condition.statusCode" clearable placeholder="报修状态">
              <el-option v-for="item in store.repairStatus" :key="item.statusCode"
                :disabled="item.statusCode == 1" :label="item.statusValue" :value="item.statusCode">
              </el-option>
            </el-select>
            <el-button type="primary" @click="queryWorkerOrder(condition.statusCode)">
              <i class="fa fa-search" aria-hidden="true"></i>&nbsp;查询状态
            </el-button>
          </el-col>
          <el-col :xs="24" :sm="6" :md="6" :lg="6" :xl="6">
            <el-select v-model="condition.repairType" clearable placeholder="报修类型">
              <el-option v-for="item in store.repairType" :key="item.typeMark"
                :label="item.typeValue" :value="item.typeMark">
              </el-option>
            </el-select>
            <el-button type="primary" @click="queryWorkerOrder(condition.repairType)">
              <i class="fa fa-search" aria-hidden="true"></i>&nbsp;查询类型
            </el-button>
          </el-col>
          <el-col :xs="24" :sm="6" :md="6" :lg="6" :xl="6">
            <div style="display: inline-block;">
              <el-input placeholder="报修地址" v-model="condition.repairAddress" clearable>
              </el-input>
            </div>
            <el-button type="primary" @click="queryWorkerOrder(condition.repairAddress)">
              <i class="fa fa-search" aria-hidden="true"></i>&nbsp;查询地址
            </el-button>
          </el-col>
          <el-col :xs="24" :sm="6" :md="6" :lg="6" :xl="6">
            <div style="display: inline-block;">
              <el-input placeholder="联系电话" v-model="condition.repairPhone" clearable>
              </el-input>
            </div>
            <el-button type="primary" @click="queryWorkerOrder(condition.repairPhone)">
              <i class="fa fa-search" aria-hidden="true"></i>&nbsp;查询电话
            </el-button>
          </el-col>
        </el-row>
        <el-row style="margin-bottom: 5px;">
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-date-picker v-model="condition.repairDate" type="datetimerange" align="right"
              unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
              :shortcuts="shortcuts">
            </el-date-picker>
            <el-button type="primary" @click="queryWorkerOrder(condition.repairDate)">
              <i class="fa fa-search" aria-hidden="true"></i>&nbsp;查询报修时间
            </el-button>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-date-picker v-model="condition.repairComplateDate" type="datetimerange"
              align="right" unlink-panels range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" :shortcuts="shortcuts">
            </el-date-picker>
            <el-button type="primary" @click="queryWorkerOrder(condition.repairComplateDate)">
              <i class="fa fa-search" aria-hidden="true"></i>&nbsp;查询完成时间
            </el-button>
          </el-col>
        </el-row>
      </div>
      <el-table
        :data="tableData.slice((pagination.currentPage - 1) * pagination.pageSize, pagination.currentPage * pagination.pageSize)"
        border v-loading="tableDataLoading" element-loading-text="拼命加载中"
        :header-cell-style="{background:'#F3F4F7',color:'#555'}"
        :default-sort="{prop: 'repairDate', order: 'descending'}" style="width: 100%">
        <el-table-column type="index" align="center" width="60" :index="tableIndex">
        </el-table-column>
        <el-table-column align="center" prop="orderId" label="单号" width="180">
        </el-table-column>
        <el-table-column align="center" prop="userEntity.nickname" label="用户名" width="180" />
        <el-table-column align="center" label="报修进度" width="400">
          <template #default="scope">
            <el-steps :active="handlerStep(scope.row).currentStep" align-center
              finish-status="success">
              <el-step v-for="(item, idx) in handlerStep(scope.row).step" :key="idx"
                :title="item.title" :status="item.status"></el-step>
            </el-steps>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="repairTypeEntity.typeValue" label="报修类型" width="180">
        </el-table-column>
        <el-table-column align="center" prop="repairAddress" label="报修地址" width="180">
        </el-table-column>
        <el-table-column align="center" prop="repairContent" width="200" label="报修问题">
        </el-table-column>
        <el-table-column align="center" prop="repairPhone" label="联系电话" width="180">
        </el-table-column>
        <el-table-column align="center" prop="repairDate" label="报修时间" width="180" sortable>
        </el-table-column>
        <el-table-column align="center" prop="repairStatusEntity.statusValue" label="报修状态"
          width="180">
          <template #default="scope">
            <el-tooltip v-if="scope.row.rejectReason != null"
              :content="`原因: ${scope.row.rejectReason}`" placement="top" effect="light"
              style="cursor: pointer;">
              <el-tag :type="repairStatusStyle(scope.row.statusCode)" effect="light"
                disable-transitions>
                {{scope.row.repairStatusEntity.statusValue}}
              </el-tag>
            </el-tooltip>
            <el-tag v-else :type="repairStatusStyle(scope.row.statusCode)" effect="light"
              disable-transitions>
              {{scope.row.repairStatusEntity.statusValue}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="repairComplateDate" label="完成时间" width="180" sortable>
        </el-table-column>
        <el-table-column align="center" prop="workerEntity.nickname" label="维修员" width="180">
          <template #default="scope">
            {{scope.row.workerEntity.workerName }} ({{ scope.row.workerEntity.nickname }})
          </template>
        </el-table-column>
        <el-table-column align="center" width="180" label="图片资料">
          <template #default="scope">
            <el-image style="width: 30px; height: 30px; margin: 5px;"
              v-for="url in scope.row.imgUrl" :key="url" :src="url" fit="fill"
              :preview-src-list="scope.row.imgUrl"></el-image>
          </template>
        </el-table-column>
        <el-table-column align="center" fixed="right" label="操作" width="180">
          <template #default="scope">
            <el-button type="primary" size="large" class="recordDetailsBtnStyle"
              @click="recordDetails(scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination @size-change="val=>pagination.pageSize = val"
          @current-change="val=>pagination.currentPage = val" :current-page="pagination.currentPage"
          :pager-count="pagination.pagerCount" :page-sizes="pagination.pageSizes"
          :page-size="pagination.pageSize" layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total" background>
        </el-pagination>
        <span class="infoTip" v-if="tableData.length > 0">共 {{tableData.length}} 条记录</span>
      </div>

    </el-card>
  </div>
</template>

<script>
import { useMainStore } from '@/js/store.js'
import { imgUrlAddress, setQps, getQps, repairStatusStyle, createOrderDetailsStep } from '@/js/public.js'
import nProgress from 'nprogress'


export default {
  data () {
    //这里存放数据
    return {
      store: useMainStore(),
      /**
       * 查询条件
       */
      condition: {
        orderId: '',
        statusCode: '',
        repairType: '',
        repairAddress: '',
        repairPhone: '',
        repairDate: '',
        repairComplateDate: '',
        queryType: true
      },
      tableData: [],
      tableDataLoading: true,
      /**
       * 订单处理进度
       */
      orderProcessEntities: [],
      pagination: {
        pageSize: 5,
        pageSizes: [5, 50, 100, 200],
        pagerCount: 5,
        currentPage: 1,
        total: 0,
      },
      repairStatusStyle,
      shortcuts: [
        {
          text: '最近一周',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            return [start, end]
          }
        },
        {
          text: '最近一个月',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            return [start, end]
          }
        },
        {
          text: '最近三个月',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            return [start, end]
          }
        }
      ],
      steps: [],
    }
  },
  /**
   * , 
   */
  //监控data中的数据变化
  watch: {
    'orderProcessEntities': 'handlerSimpleOrderDetailsStep',
    'store.steps': function (newVal) {
      this.steps = newVal;
    },
    'store.workerOrders': function (newVal) {
      this.tableData = newVal;
    }
  },
  activated () {
    console.log('工人端报修记录页面被激活，重新获取数据');
    // 重新获取数据而不只是强制更新视图
    this.queryWorkerOrder();
    this.$forceUpdate();
  },
  beforeDestroy() {
    // 清理可能存在的ResizeObserver
    if (window.observer) {
      try {
        window.observer.disconnect();
      } catch (e) {
        console.log('清理observer时发生错误:', e);
      }
    }
    
    // 清理可能的其他资源
    this.tableData = null;
    this.orderProcessEntities = null;
  },
  //方法集合
  methods: {
    getRepairStatus() {
      // 修改：确保状态数据能正确加载
      if (this.store.repairStatus && this.store.repairStatus.length > 0) {
        console.log("从store中获取报修状态数据:", this.store.repairStatus);
        return;
      }
      
      console.log("开始获取报修状态数据");
      this.axios.get("/userHome/repairStatus").then(res => {
        console.log("报修状态API响应:", res);
        
        if (res.data && res.data.code === 43000 && res.data.data) {
          console.log("获取到报修状态数据:", res.data.data);
          
          // 确保数据格式正确
          if (Array.isArray(res.data.data)) {
            this.store.repairStatus = res.data.data;
            
            // 强制更新视图
            this.$forceUpdate();
            
            // 打印已设置的状态数据
            console.log("已设置报修状态数据:", this.store.repairStatus);
          } else {
            console.error("报修状态数据格式错误，不是数组:", res.data.data);
          }
        } else {
          console.error("报修状态数据获取失败或为空", res.data);
          
          // 设置一些静态数据，以防API无响应
          this.store.repairStatus = [
            { statusCode: 2, statusValue: "已接单" },
            { statusCode: 3, statusValue: "维修中" },
            { statusCode: 4, statusValue: "维修完成" },
            { statusCode: 5, statusValue: "已拒绝" }
          ];
          console.log("已设置静态报修状态数据");
          
          // 强制更新视图
          this.$forceUpdate();
        }
      }).catch(err => {
        console.error("获取报修状态数据出错:", err);
        
        // 设置一些静态数据，以防API出错
        this.store.repairStatus = [
          { statusCode: 2, statusValue: "已接单" },
          { statusCode: 3, statusValue: "维修中" },
          { statusCode: 4, statusValue: "维修完成" },
          { statusCode: 5, statusValue: "已拒绝" }
        ];
        console.log("已设置静态报修状态数据");
        
        // 强制更新视图
        this.$forceUpdate();
      });
    },
    
    getRepairType() {
      // 修改：确保类型数据能正确加载
      if (this.store.repairType && this.store.repairType.length > 0) {
        console.log("从store中获取报修类型数据:", this.store.repairType);
        return;
      }
      
      console.log("开始获取报修类型数据");
      this.axios.get("/userHome/repairType").then(res => {
        if (res.data && res.data.data) {
          console.log("获取到报修类型数据:", res.data.data);
        this.store.repairType = res.data.data;
        } else {
          console.error("报修类型数据获取失败或为空");
        }
      }).catch(err => {
        console.error("获取报修类型数据出错:", err);
      });
    },
    /**
     * @description: 根据表格每行记录orderId索引对应步骤条状态信息
     * @param {*} row
     * @return {*}
     * @author: 小花
     */
    handlerStep (row) {
      return this.steps.find(item => item.orderId == row.orderId)
    },
    /**
     * @description: 根据订单状态记录，解析出对应步骤条元素所需数据
     * @param {*}
     * @return {*}
     * @author: 小花
     */
    handlerSimpleOrderDetailsStep () {
      this.steps = createOrderDetailsStep(this.orderProcessEntities);
      this.store.steps = this.steps;
    },
    /**
     * @description: 进入订单详情页
     * @param {*} row
     * @return {*}
     * @author: 小花
     */
    recordDetails (row) {

      let data = JSON.parse(JSON.stringify(row));

      this.store.recordDetails = {
        data,
        step: this.handlerStep(row)
      }
      this.$router.push("record_details");
    },
    /**
     * @description: 查询条件重置
     * @param {*}
     * @return {*}
     * @author: 小花
     */
    reset () {
      for (let key in this.condition) {
        if (key == 'queryType') continue;
        this.condition[key] = '';
      }
      this.queryWorkerOrder();
    },

    /**
     * @description: 查询维修员订单记录
     * @param {*} value
     * @return {*}
     * @author: 小花
     */
    queryWorkerOrder (value = null) {
      /**限制过量查询数据 */
      if (getQps('queryWorkerOrder')) return;
      setQps('queryWorkerOrder', 3);
      nProgress.start()

      let map = {};
      if (this.condition.queryType != true) {
        /**
         * 组合查询
         */
        map = this.condition;
      } else {
        /**
         * 独立查询
         */
        if (value != null)
          for (let key in this.condition) {
            if (this.condition[key] == value) {
              map[key] = value;
              break;
            }
          }
      }
      delete map.queryType;

      this.axios.post("/workerHome/queryWorkerOrder", map).then(res => {

        this.tableData = res.data.data?.repairOrdersEntities || [];
        this.orderProcessEntities = res.data.data?.orderProcessEntities || [];

        this.tableData.forEach((item, idx) => {
          this.tableData[idx].imgUrl = imgUrlAddress(item.imgUrl);
        });

        this.store.workerOrders = this.tableData;

        this.pagination.currentPage = 1;
        this.pagination.total = this.tableData.length;
        this.tableDataLoading = false;
        nProgress.done()
      })
    },
    /**
     * @description: 表格行数索引
     * @param {*} index
     * @return {*}
     * @author: 小花
     */
    tableIndex (index) {
      return (index + 1) + (this.pagination.currentPage - 1) * this.pagination.pageSize;
    },
    // 如果有导航到报修中心的方法，修改为使用延迟导航
    goToRepairCenter() {
      // 先显示加载状态
      nProgress.start();
      
      // 延迟导航以确保组件完全卸载
      setTimeout(() => {
        this.$router.push('/workerHome/worker_repairCenter');
        nProgress.done();
      }, 100);
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created () {
    this.queryWorkerOrder();
    this.store.recordDetails = {};
    this.getRepairType();
    this.getRepairStatus(); // 添加获取报修状态的方法调用
  }
}
</script>

<style lang='scss' scoped>
//@import url(); 引入公共css类
.repairRecord_container {
  .el-row {
    .el-col {
      display: flex;
      align-items: center;
      margin-bottom: 1rem;
    }
  }
  
  .pagination {
    display: flex;
    justify-content: center;
    margin-top: 30px;
    margin-bottom: 30px;
    padding: 20px;
    background-color: #fff;
    align-items: center;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    border: 1px solid #ebeef5;
    flex-wrap: wrap;
    gap: 15px;
    min-height: 70px;
    
    :deep(.el-pagination) {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      gap: 8px;
      
      .btn-prev, .btn-next {
        min-width: 32px;
        height: 32px;
        border-radius: 6px;
        transition: all 0.3s;
        
        &:hover {
          transform: translateY(-1px);
          box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }
      }
      
      .el-pager {
        li {
          min-width: 32px;
          height: 32px;
          border-radius: 6px;
          transition: all 0.3s;
          
          &:hover:not(.active) {
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
          }
        }
      }
      
      .el-pagination__sizes {
        .el-select .el-input .el-input__wrapper {
          height: 32px;
          border-radius: 6px;
        }
      }
      
      .el-pagination__jump {
        .el-input .el-input__wrapper {
          height: 32px;
          border-radius: 6px;
          width: 50px;
        }
      }
    }
    
    .infoTip {
      color: #606266;
      font-size: 14px;
      background-color: #f5f7fa;
      border-radius: 6px;
      padding: 8px 12px;
      white-space: nowrap;
    }
  }
  
  // 移动端样式
  @media screen and (max-width: 768px) {
    .pagination {
      margin: 15px 0;
      padding: 15px 10px;
      flex-direction: column;
      gap: 10px;
      
      :deep(.el-pagination) {
        font-size: 12px;
        justify-content: center;
        
        .btn-prev, .btn-next {
          min-width: 28px;
          height: 28px;
        }
        
        .el-pager {
          li {
            min-width: 28px;
            height: 28px;
            margin: 0 1px;
          }
        }
        
        .el-pagination__sizes {
          .el-select .el-input .el-input__wrapper {
            height: 28px;
            font-size: 12px;
          }
        }
        
        .el-pagination__jump {
          .el-input .el-input__wrapper {
            height: 28px;
            width: 40px;
            font-size: 12px;
          }
        }
      }
      
      .infoTip {
        font-size: 12px;
        padding: 6px 10px;
      }
    }
  }
  
  .el-table {
    .recordDetailsBtnStyle {
      width: 100%;
      letter-spacing: 1rem;
      text-align: center;
      text-indent: 1rem;
    }
  }
}
</style>